import {Button, Empty, message, Spin, Table, Tag, Typography, Popconfirm, Space} from "antd";
import {useEffect, useState} from "react";
import {
    DeleteOutlined,
    EditOutlined,
    InfoOutlined,
    ReloadOutlined,
    ExclamationCircleOutlined,
    PlusCircleOutlined
} from "@ant-design/icons";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import TopicCreate from "../../../components/console/mq/topicCreate";
import TopicEdit from "../../../components/console/mq/topicEdit";

const {Title, Text} = Typography;

/**
 * 主题管理页面组件
 * 优化点：刷新按钮移除旋转效果，增强交互质感
 */
const ConsoleTopicPage = () => {
    // 消息提示组件
    const [messageApi, contextHolder] = message.useMessage();

    // 主题列表数据状态
    const [topicList, setTopicList] = useState([]);

    // 加载状态管理
    const [loading, setLoading] = useState(false);

    // 创建主题模态框开关
    const [createTopicVisible, setCreateTopicVisible] = useState(false);

    // 编辑主题模态框开关
    const [editTopicVisible, setEditTopicVisible] = useState(false);
    // 编辑主题数据
    const [topicDetail, setTopicDetail] = useState({});

    /**
     * 查询全部topic列表
     * 包含加载状态管理和错误处理
     */
    const searchAllTopicList = () => {
        setLoading(true);
        RequestUtils.post(RequestApis.messageManage.searchAllTopic, {})
            .then(res => {
                setTopicList(res.data.data || []);
                setLoading(false);
            })
            .catch(err => {
                messageApi.error(err.message || "查询主题列表失败");
                setLoading(false);
            });
    };

    /**
     * 删除主题
     * @param topic
     */
    const removeTopic = (topic) => {
        RequestUtils.post(RequestApis.messageManage.removeTopic, {
            topic: topic
        }).then(res => {
            searchAllTopicList();
            messageApi.success("删除主题成功");
        }).catch(err => messageApi.error(err.message));
    }

    /**
     * 组件挂载时自动加载数据
     */
    useEffect(() => {
        searchAllTopicList();
        // eslint-disable-next-line
    }, []);

    /**
     * 刷新主题列表数据
     */
    const handleRefresh = () => {
        searchAllTopicList();
        messageApi.success("已刷新主题列表");
    };

    /**
     * 表格列配置
     */
    const columns = [
        {
            title: "序号",
            key: "index",
            width: "60px",
            align: "center",
            render: (_, __, index) => (
                <Text style={{
                    fontSize: "14px",
                    fontWeight: 600,
                }}>
                    {index + 1}
                </Text>
            )
        },
        {
            title: "主题名称",
            dataIndex: "topic",
            key: "topic",
            ellipsis: true,
            width: "240px",
            render: (text) => (
                <Text style={{
                    fontSize: "15px",
                    fontWeight: 600,
                    color: "#0080ff"
                }}>
                    {text}
                </Text>
            ),
        },
        {
            title: "主题描述",
            dataIndex: "description",
            key: "description",
            ellipsis: true,
            width: "450px",
            render: (text) => (
                text ? (
                    <Text style={{
                        fontSize: "14px",
                        color: "#ff007f",
                        lineHeight: 1.6
                    }}>
                        {text}
                    </Text>
                ) : (
                    <Tag
                        color="default"
                        icon={<InfoOutlined/>}
                        style={{fontSize: "12px", marginTop: 3}}
                    >
                        无描述信息
                    </Tag>
                )
            ),
        },
        {
            title: "创建时间",
            dataIndex: "createdTime",
            key: "createdTime",
            width: "240px",
            render: (time) => {
                if (!time) {
                    return (
                        <Tag
                            color="default"
                            style={{fontSize: "12px", marginTop: 3}}
                        >
                            未设置
                        </Tag>
                    );
                }
                return (
                    <Text style={{
                        fontSize: "14px",
                        color: "#009999"
                    }}>
                        {time}
                    </Text>
                );
            },
        },
        {
            title: "操作",
            key: "action",
            render: (_, record) => (
                <Space size="small" style={{width: '100%', justifyContent: 'flex-start'}}>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EditOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#fa8c16',
                            backgroundColor: 'rgba(250, 140, 22, 0.05)',
                            border: '1px solid #ffbb96',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px',
                            whiteSpace: 'nowrap'
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                            e.currentTarget.style.transform = 'translateY(-2px)';
                            e.currentTarget.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                            e.currentTarget.style.transform = 'translateY(0)';
                            e.currentTarget.style.boxShadow = 'none';
                        }}
                        onClick={() => {
                            setTopicDetail(record);
                            setEditTopicVisible(true);
                        }}
                    >
                        编辑
                    </Button>

                    <Popconfirm
                        title="确认删除"
                        description="此操作将永久删除该主题，删除后不可恢复，是否继续？"
                        icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
                        onConfirm={() => removeTopic(record.topic)}
                        okText="确认"
                        cancelText="取消"
                        placement="left"
                    >
                        <Button
                            size={"small"}
                            type="text"
                            icon={<DeleteOutlined/>}
                            style={{
                                fontSize: '14px',
                                color: '#EC4848',
                                backgroundColor: '#FFE9E9',
                                border: '1px solid #FFCCCC',
                                borderRadius: '6px',
                                padding: '4px 12px',
                                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '4px',
                                whiteSpace: 'nowrap'
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.backgroundColor = '#FFE0E0';
                                e.currentTarget.style.transform = 'translateY(-2px)';
                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(236, 72, 72, 0.2)';
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.backgroundColor = '#FFE9E9';
                                e.currentTarget.style.transform = 'translateY(0)';
                                e.currentTarget.style.boxShadow = 'none';
                            }}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <div style={{
            padding: "24px"
        }}>
            {contextHolder}

            {/* 页面标题和操作区 */}
            <div style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: "20px",
                paddingBottom: "16px",
                borderBottom: "1px solid #f0f0f0"
            }}>
                <Title level={4} style={{
                    margin: 0,
                    color: "#1890ff",
                    fontWeight: 600
                }}>
                    主题 Topic 列表
                </Title>
                {/* 优化后的刷新按钮 - 移除旋转效果，增强交互质感 */}
                <Button
                    icon={<ReloadOutlined />}
                    onClick={handleRefresh}
                    color='pink'
                    variant={"solid"}
                    style={{width: '180px'}}
                >
                    <span style={{fontWeight: "bold", color: 'white'}}>刷新</span>
                </Button>
            </div>

            {/* 操作按钮区 */}
            <div style={{
                marginBottom: "16px"
            }}>
                <Button
                    color='purple'
                    variant='solid'
                    onClick={() => setCreateTopicVisible(true)}
                    style={{width: '240px'}}
                >
                    <PlusCircleOutlined style={{marginRight: '8px'}}/>
                    创建Topic
                </Button>
            </div>

            {/* 表格内容区域 */}
            <div style={{
                backgroundColor: "#fff",
                border: "1px solid #e8e8e8",
                borderRadius: "8px",
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.04)",
                overflow: "hidden"
            }}>
                <Spin spinning={loading} tip="正在加载主题数据...">
                    <Table
                        columns={columns}
                        dataSource={topicList.map(item => ({...item, key: item.topic}))}
                        pagination={false}
                        bordered={false}
                        rowKey="topic"
                        locale={{emptyText: <Empty description="暂无主题数据"/>}}
                        onRow={(record) => ({
                            onMouseEnter: (e) => {
                                e.currentTarget.style.backgroundColor = "#f0f7ff";
                                e.currentTarget.style.transition = "backgroundColor 0.2s ease";
                            },
                            onMouseLeave: (e) => {
                                e.currentTarget.style.backgroundColor = "";
                            },
                        })}
                        style={{
                            fontSize: "14px"
                        }}
                        components={{
                            Header: {
                                style: {
                                    backgroundColor: "#f5f7fa",
                                    fontWeight: 500,
                                    borderBottom: "1px solid #e8e8e8"
                                }
                            },
                            Body: {
                                style: {
                                    borderBottom: "1px solid #f0f0f0"
                                }
                            }
                        }}
                        cellStyle={{
                            padding: "12px 16px",
                            borderBottom: "1px solid #f5f5f5"
                        }}
                    />
                </Spin>
            </div>

            {/* 创建topic模态框 */}
            <TopicCreate
                visible={createTopicVisible}
                setVisible={setCreateTopicVisible}
                searchAllTopicList={searchAllTopicList}
            />

            {/* 编辑topic模态框 */}
            <TopicEdit
                visible={editTopicVisible}
                setVisible={setEditTopicVisible}
                searchAllTopicList={searchAllTopicList}
                topicDetail={topicDetail}
            />
        </div>
    );
};

export default ConsoleTopicPage;